package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.area.model.response.AreaVO;
import com.wing.area.service.AreaService;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.dict.model.entity.DictLabel;
import com.wing.purchase.dao.SupplierContactsDao;
import com.wing.purchase.model.entity.SupplierCategory;
import com.wing.purchase.model.entity.SupplierContacts;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.model.entity.SupplierLevel;
import com.wing.purchase.model.request.SupplierContactsForm;
import com.wing.purchase.model.request.SupplierDetailConcatExcelInForm;
import com.wing.purchase.model.request.SupplierDetailExcelInForm;
import com.wing.purchase.model.response.SupplierContactsVO;
import com.wing.purchase.model.response.SupplierInfoVO;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.web.excel.DownExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 供应商联系人表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SupplierContactsServiceImpl extends ServiceImpl<SupplierContactsDao, SupplierContacts> implements SupplierContactsService {

    @Resource
    UserClient userClient;

    @Override
    public int add(SupplierContactsForm supplierContactsForm) {
        //添加用户
//        User user = new User();
//        user.setUserRoleCode("SUPPLIER_USER");
//        user.setNickname(supplierContactsForm.getContactName());
//        user.setUsername(supplierContactsForm.getPhoneNumber());
//        user.setPhone(supplierContactsForm.getPhoneNumber());
//        userClient.addThirdUser(user);

        //校验
        SupplierContacts supplierContacts =new SupplierContacts();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SupplierContacts.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierContactsForm, supplierContacts, copyOptions);
        return baseMapper.insert(supplierContacts);
    }

    @Override
    public List<SupplierContactsVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<SupplierContactsVO> pageList4app(Page page, Map<String, Object> params) {
        List<SupplierContactsVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public SupplierContactsVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public boolean removeBySupId(Long supplierInfoId) {
        return baseMapper.removeBySupId(supplierInfoId);
    }

    @Autowired
    SupplierCategoryService supplierCategoryService;

    @Autowired
    SupplierLevelService supplierLevelService;

    @Autowired
    private AreaService areaService;

    @Autowired
    SupplierInfoService supplierInfoService;

    @Override
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"供应商公司名称","联系人姓名","联系人电话","职务","身份证号码","省","市","区/县","联系地址","邮箱地址"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        //查询所有供应商
        Page<SupplierInfoVO> pg = new Page<>(1, 999);
        Map<String, Object> params = new HashMap<>();
        params.put("status", SupplierInfo.Status.pass);
        IPage<SupplierInfoVO> list = supplierInfoService.pageList4app(pg, params);
        List<SupplierInfoVO> supplierInfoVOList = list.getRecords();
  /*      String[] natureData = new String[]{supplierInfoVOList.stream().map(t -> t.getCorporateName()).collect(Collectors.joining(","))};
        indexArr.add("0");
        downData.add(natureData);
*/

         if (CollectionUtil.isNotEmpty(supplierInfoVOList)) {
            for (SupplierInfoVO dictLabel : supplierInfoVOList) {
                tempStr.append(dictLabel.getCorporateName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("0");
        }


        // 获取所有省份
        List<AreaVO> provinceList = areaService.getProvinceList();
        if (CollectionUtil.isNotEmpty(provinceList)) {
            for (AreaVO dictLabel : provinceList) {
                tempStr.append(dictLabel.getName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("5");
        }

        // 将省份名称加入downData，并为省份列添加索引
/*
        String provinces = provinceList.stream().map(AreaVO::getName).collect(Collectors.joining(","));
        downData.add(new String[]{provinces});
        indexArr.add("5"); // 省份列索引
*/
        DownExcelUtil.createExcelTemplate(response, request, "供应商联系人导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    @Override
    public JsonResult importExcel(List<SupplierDetailConcatExcelInForm> list) {


        int i = 1;
        for (SupplierDetailConcatExcelInForm supplierDetailConcatExcelInForm : list) {

            if (supplierDetailConcatExcelInForm.getCorporateId()==null) {
                throw new BusinessException(300, "第" + i + "行【供应商名称】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailConcatExcelInForm.getContactName())) {
                throw new BusinessException(300, "第" + i + "行【联系人】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailConcatExcelInForm.getPhoneNumber())) {
                throw new BusinessException(300, "第" + i + "行【联系人电话】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailConcatExcelInForm.getJob())) {
                throw new BusinessException(300, "第" + i + "行【职务】未输入数据");
            }


            Page<SupplierInfoVO> pg = new Page<>(1, 999);
            Map<String, Object> params = new HashMap<>();
            params.put("status", SupplierInfo.Status.pass);
            IPage<SupplierInfoVO> list2 = supplierInfoService.pageList4app(pg, params);
            List<SupplierInfoVO> supplierInfoVOList = list2.getRecords();
            SupplierInfoVO resultBig = supplierInfoVOList.stream()
                    .filter(provinces -> provinces.getCorporateName().equals(supplierDetailConcatExcelInForm.getCorporateId()))
                    .findFirst()
                    .orElse(null);



            //校验
            SupplierContacts supplierContacts =new SupplierContacts();

            if(resultBig!=null){
                supplierContacts.setCorporateId(resultBig.getId());
            }

            List<AreaVO> provinceList = areaService.getProvinceList();
            AreaVO result2 = provinceList.stream()
                    .filter(provinces -> provinces.getName().equals(supplierDetailConcatExcelInForm.getProvinceId()))
                    .findFirst()
                    .orElse(null);

            if(result2!=null){
                supplierContacts.setProvinceId(Long.valueOf(result2.getId()));
                List<AreaVO> cityList = areaService.getCityList(result2.getId()); // 根据省份ID获取城市列表
                AreaVO cityResult = cityList.stream()
                        .filter(citys -> citys.getName().equals(supplierDetailConcatExcelInForm.getCityId()))
                        .findFirst()
                        .orElse(null);

                if(cityResult!=null){
                    supplierContacts.setCityId(Long.valueOf(cityResult.getId()));
                    if(cityResult!=null){
                        supplierContacts.setCityId(Long.valueOf(cityResult.getId()));
                    }

                    List<AreaVO> areaVOList = areaService.getAreaList(result2.getId()); // 根据省份ID获取城市列表
                    AreaVO areaVO = areaVOList.stream()
                            .filter(areas -> areas.getName().equals(supplierDetailConcatExcelInForm.getAreaId()))
                            .findFirst()
                            .orElse(null);

                    if(areaVO!=null){
                        supplierContacts.setAreaId(Long.valueOf(areaVO.getId()));
                    }
                }
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(SupplierContacts.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(supplierDetailConcatExcelInForm, supplierContacts, copyOptions);

                //添加用户
                User user = new User();
                user.setUserRoleCode("SUPPLIER_USER");
                user.setNickname(supplierDetailConcatExcelInForm.getContactName());
                user.setUsername(supplierDetailConcatExcelInForm.getPhoneNumber());
                user.setPhone(supplierDetailConcatExcelInForm.getPhoneNumber());
                userClient.addThirdUser(user);

                baseMapper.insert(supplierContacts);
            }

        }

        return null;
    }


}
